﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using IndexMarkSilverlightClient.Classes;
using System.Windows.Data;
using IndexMarkSilverlightClient;


namespace IndexMarkSilverlightClient.Views
{
    using System.Windows;
    using IndexMarkSilverlightClient.IndexMarkServiceReference;
    using SharedCode.Common;
    using SharedCode;

    public class InputMainViewModel : ViewModelBase
    {
        #region DataMembers

        private IndexMarkServiceClient client = new IndexMarkServiceClient();

        private User user;
        public User User
        {
            get
            {
                return user;
            }
            set
            {
                user = value;
                PropertyChangedInit("User");
            }
        }

        //устанавливает видимость показателей в зависимости от выбранного режима
        public bool AllVisible
        {
            set
            {
                VisibilitySections = ObjectClone.Clone<ObservableCollection<Section>>(sections);
                for (int i = 0; i < VisibilitySections.Count; i++)
                {
                    Section Sec = VisibilitySections[i];
                    if (!value)
                    {
                        if (!Sec.IsResponsible)
                        {
                            VisibilitySections.RemoveAt(i);
                            i--;
                        }
                        else
                        {
                            CollapseChilds(Sec);
                        }
                    }
                }

                PropertyChangedInit("VisibilitySections");
            }
        }

        private void CollapseChilds(Section S)
        {
            for (int i = 0; i < S.Childs.Count; i++)
            {
                IndexMarkItem item = S.Childs[i] as IndexMarkItem;
                if (!item.IsResponsible)
                {
                    S.Childs.RemoveAt(i);
                    i--;
                }
                if (item is Section)
                {
                    CollapseChilds(item as Section);
                }
            }
        }

        private ObservableCollection<Section> sections = new ObservableCollection<Section>();

        public ObservableCollection<Section> Sections
        {
            get
            {
                return sections;
            }
        }

        public ObservableCollection<Section> VisibilitySections
        {
            get;
            set;
        }

        ObservableCollection<RespondentAnswers> respAnswers = new ObservableCollection<RespondentAnswers>();

        public PagedCollectionView RespAnswers
        {
            get
            {
                PagedCollectionView RA = new PagedCollectionView(this.respAnswers);
                RA.GroupDescriptions.Add(new PropertyGroupDescription("Resp.Department.Name"));
                RA.SortDescriptions.Add(new SortDescription("Resp.FullName", ListSortDirection.Ascending));
                return RA;
            }
        }

        private ObservableCollection<Department> departments = new ObservableCollection<Department>();

        public ObservableCollection<Department> Departments
        {
            get
            {
                return departments;
            }
        }

        private Department currentDep;

        public Department CurrentDep
        {
            get
            {
                if (currentDep == null) return new Department
                {
                    IDDepartment = null
                };
                return currentDep;
            }
            set
            {
                currentDep = value;
                PropertyChangedInit("CurrentDep");
            }
        }

        private Characteristic currentChar;

        public Characteristic CurrentChar
        {
            get
            {
                return currentChar;
            }
            set
            {
                currentChar = value;
                client.GetRespAnswersAsync(currentChar.ID, CurrentDep.IDDepartment);
            }
        }

        //private Respondent currentResp;

        //public Respondent CurrentResp
        //{
        //    get
        //    {
        //        return currentResp;
        //    }
        //    set
        //    {
        //        currentResp = value;
        //        PropertyChangedInit("CurrentResp");
        //    }
        //}

        private Term currentTerm;

        public Term CurrentTerm
        {
            get
            {
                return currentTerm;
            }
            set
            {
                //this.Clear();
                if (value == null)
                {
                    CMessage.Show("Выберите период");
                }
                else
                {
                    CMessage.Hide();
                    currentTerm = value;
                    PropertyChangedInit("CurrentTerm");
                    client.GetTreeAsync(currentTerm.IDTerm);
                    client.GetDepartmentsListAsync(currentTerm.IDTerm);
                }
            }
        }

        //    private bool isYesNoUnit;

        //    public bool IsYesNoUnit
        //    {
        //        get 
        //        {
        //            return isYesNoUnit; 
        //        }
        //        set
        //        {
        //            isYesNoUnit = value;
        //            PropertyChangedInit("IsYesNoUnit");
        //        }
        //    }

        #endregion

        /// <summary>
        /// конструктор класса. Подписка на события загрузки данных с сервиса
        /// </summary>
        public InputMainViewModel()
        {
            client.GetDepartmentsListCompleted += client_GetDepartmentsListCompleted;
            client.GetTreeCompleted += client_GetTreeCompleted;
            client.GetRespAnswersCompleted += client_GetRespAnswersCompleted;
        }

        void client_GetRespAnswersCompleted(object sender, GetRespAnswersCompletedEventArgs e)
        {
            respAnswers = e.Result;

            SetRespondentsHasEdit();

            PropertyChangedInit("RespAnswers");
            LoadCompletedInit(typeof(RespondentAnswers));
        }

        /// <summary>
        /// метод устанавливает возможность редактирования респондентов
        /// </summary>
        private void SetRespondentsHasEdit()
        {

            //флаг показывает возможность редактирования по дате
            bool HasEditDate = currentTerm.StartFill <DateTime.Now && currentTerm.StopFill > DateTime.Now;

            foreach (RespondentAnswers RA in respAnswers)
            {
                ///???
                //if (currentChar.Order == "4.1.12" && User.Containts(currentChar, RA.Resp)
                //    && DateTime.Now < DateTime.Parse("08.10.2011")) 
                //    RA.Resp.HasEdit = true;
                //else
               
                RA.Resp.HasEdit =  (User.IsSupervisor || HasEditDate && (User.Containts(currentChar, RA.Resp)));
                //RA.Resp.HasEdit = true;
            }
        }

        void client_GetTreeCompleted(object sender, GetTreeCompletedEventArgs e)
        {
            sections = e.Result;
            foreach (Section S in e.Result)
            {
                ImageRepository.Instance.SetTreeItemImage(S);
                SetImageResponsibleItems(S as Section);
            }

            VisibilitySections = ObjectClone.Clone<ObservableCollection<Section>>(sections);

            PropertyChangedInit("VisibilitySections");
            //LoadCompletedInit(typeof(Section));
        }

        void client_GetDepartmentsListCompleted(object sender, GetDepartmentsListCompletedEventArgs e)
        {
            departments = e.Result;
            PropertyChangedInit("Departments");
            LoadCompletedInit(typeof(Department));
        }

        /// <summary>
        /// метод обходящий дерево
        /// </summary>
        /// <param name="S">Очередной узел дерева</param>
        /// <remarks>
        /// Метод нужен, чтоб прописать каждому узлу путь к извображению
        /// </remarks>
        /// <seealso cref="Classes\ImageRepository.cs"/>
        private void SetImageResponsibleItems(Section S)
        {
            S.ImagePath = ImageRepository.Instance.SetTreeItemImage(S);
            foreach (IndexMarkItem item in S.Childs)
            {
                item.ImagePath = ImageRepository.Instance.SetTreeItemImage(item);
                if (item is Section)
                {
                    SetImageResponsibleItems(item as Section);
                }
                if (item is Characteristic)
                {
                    var c = item as Characteristic;
                    var r = User.IsResponsible(c);
                    //MessageBox.Show(c.Name + r.ToString());
                    c.IsResponsible = r;
                }
            }
        }

        public void LoadAnswers()
        {
            client.GetRespAnswersAsync(currentChar.ID, CurrentDep.IDDepartment);
        }
    }
}
